﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;

namespace SmartVault.Core
{
    /// <summary>
    /// AbsolutePath
    /// 
    /// Provides a pathing class for easy handling of non host portion of a URI path.
    /// These paths are case insensitive.
    /// 
    /// This path is rooted.
    /// 
    /// Example: /pth/My Account
    /// </summary>
    public class AbsolutePath : IPath
    {
        #region Private Members
        private string _path;
        private List<string> _elements = new List<string>();
        private static readonly AbsolutePath _root = new AbsolutePath("/");
        #endregion

        /// <summary>
        /// Root
        /// 
        /// The root path.
        /// </summary>
        public static AbsolutePath Root { get { return _root; } }

        #region Constructor
        /// <summary>
        /// Constructor
        /// 
        /// If the path is not rooted at '/' this will throw.
        /// </summary>
        /// <param name="path"></param>
        public AbsolutePath(string path)
        {
            if (string.IsNullOrEmpty(path) || path[0] != '/') throw new ArgumentException("path");

            if (path.Length > 1 && path[path.Length - 1] == '/')
            {
                path = path.Substring(0, path.Length - 1);
            }

            if (path.Length > 1)
            {
                int start = 1;
                int length = 0;

                for (int i = 1; i < path.Length; ++i)
                {
                    if (path[i] == '/')
                    {
                        string tmp = path.Substring(start, length);
                        if (string.IsNullOrEmpty(tmp)) throw new ArgumentException("path");
                        _elements.Add(tmp);
                        length = 0;
                        start = i + 1;
                    }
                    else
                    {
                        ++length;
                    }
                }
                _elements.Add(path.Substring(start, length));
            }

            _path = path;
        }

        /// <summary>
        /// Constructor
        /// 
        /// Merge two lists of elements
        /// </summary>
        /// <param name="elements1">List 1 of elements</param>
        /// <param name="elements2">List 2 of elements</param>
        public AbsolutePath(IList<string> elements1, IList<string> elements2)
        {
            StringBuilder bld = new StringBuilder();
            for (int i = 0; i < elements1.Count; ++i)
            {
                if (string.IsNullOrEmpty(elements1[i])) throw new InvalidOperationException();

                bld.AppendFormat("/{0}", elements1[i]);
                _elements.Add(elements1[i]);
            }

            for (int i = 0; i < elements2.Count; ++i)
            {
                if (string.IsNullOrEmpty(elements2[i])) throw new InvalidOperationException();

                bld.AppendFormat("/{0}", elements2[i]);
                _elements.Add(elements2[i]);
            }

            _path = bld.ToString();

            if (_elements.Count == 0)
            {
                _path = "/";
            }
        }

        /// <summary>
        /// Constructor
        /// 
        /// Build from a portion of elements
        /// </summary>
        /// <param name="elements">Element List</param>
        /// <param name="start">Consume from this offset</param>
        /// <param name="count">Number of elements to consume</param>
        public AbsolutePath(IList<string> elements, int start, int count)
        {
            StringBuilder bld = new StringBuilder();
            for (int i = start; i < start + count; ++i)
            {
                if (string.IsNullOrEmpty(elements[i])) throw new InvalidOperationException();

                bld.AppendFormat("/{0}", elements[i]);
                _elements.Add(elements[i]);
            }

            _path = bld.ToString();

            if (_elements.Count == 0)
            {
                _path = "/";
            }
        }
        #endregion

        #region Public Properties
        /// <summary>
        /// Parent path. Throws an exception if this is root.
        /// </summary>
        public AbsolutePath Parent
        {
            get
            {
                if (Count == 0)
                {
                    throw new ArgumentException();
                }
                else if (Count == 1)
                {
                    return AbsolutePath.Root;
                }
                else
                {
                    return new AbsolutePath(_elements, 0, _elements.Count - 1);
                }
            }
        }

        /// <summary>
        /// Return Last Element
        /// </summary>
        public string Last
        {
            get
            {
                return this[Count - 1];
            }
        }

        /// <summary>
        /// Count
        /// </summary>
        public int Count { get { return _elements.Count; } }

        #endregion

        #region Public Methods

        /// <summary>
        /// Convert to Relative Path
        /// </summary>
        /// <returns></returns>
        public RelativePath ToRelative()
        {
            return new RelativePath(_elements, 0, _elements.Count);
        }

        /// <summary>
        /// Provide a subpath
        /// </summary>
        /// <param name="startIndex">Index to start at</param>
        /// <returns></returns>
        public RelativePath Subpath(int startIndex)
        {
            return new RelativePath(_elements, startIndex, _elements.Count - startIndex);
        }

        /// <summary>
        /// Provide a subpath
        /// </summary>
        /// <param name="startIndex">Index to start at</param>
        /// <param name="length">Length of subpath</param>
        /// <returns></returns>
        public RelativePath Subpath(int startIndex, int length)
        {
            return new RelativePath(_elements, startIndex, length);
        }

        /// <summary>
        /// Append Element
        /// </summary>
        /// <param name="element">Element to append</param>
        /// <returns></returns>
        public AbsolutePath Append(string element)
        {
            if (string.IsNullOrEmpty(element)) throw new ArgumentException("element");
            if (element[0] == '/') throw new ArgumentException("element");

            return new AbsolutePath(_path == "/" ? "/" + element : _path + '/' + element);
        }

        /// <summary>
        /// Append Relative Path
        /// </summary>
        /// <param name="path">Relative Path to Append</param>
        /// <returns></returns>
        public AbsolutePath Append(RelativePath path)
        {
            if (path == null) throw new ArgumentException("path");
            return new AbsolutePath(_path == "/" ? "/" + path.ToString() : _path + '/' + path.ToString());
        }

        IPath IPath.Append(string element)
        {
            return this.Append(element);
        }

        IPath IPath.Append(RelativePath path)
        {
            return this.Append(path);
        }

        /// <summary>
        /// Array Accessor
        /// </summary>
        /// <param name="index">Index</param>
        /// <returns></returns>
        public string this[int index]
        {
            get
            {
                return _elements[index];
            }
        }

        /// <summary>
        /// GetHashCode()
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            return _path.GetHashCode();
        }

        /// <summary>
        /// Determines if this object equals another object.
        /// This is done by converting the rhs using .ToString().ToLower() and
        /// performing a string comparision.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            string lhs = this.ToString();
            string rhs = obj == null ? string.Empty : obj.ToString();
            return lhs.ToLower() == rhs.ToLower();
        }

        /// <summary>
        /// Equal Operator
        /// </summary>
        /// <param name="p1"></param>
        /// <param name="p2"></param>
        /// <returns></returns>
        public static bool operator ==(AbsolutePath p1, AbsolutePath p2)
        {
            return ((object)p1) == null ? ((object)p2) == null : p1.Equals(p2);
        }
        /// <summary>
        /// Not Equal Operator
        /// </summary>
        /// <param name="p1"></param>
        /// <param name="p2"></param>
        /// <returns></returns>
        public static bool operator !=(AbsolutePath p1, AbsolutePath p2)
        {
            return ((object)p1) == null ? ((object)p2) != null : !p1.Equals(p2);
        }

        /// <summary>
        /// ToString()
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return _path;
        }
        #endregion
    }
}
